import React, { useState, useEffect } from 'react';
import { Button, Divider } from 'antd';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, use_olreport_bybbbm,
  convertISODateTimeToYYYYMMDD,
  addkey_for_mxdata,
  use_dict_byzdmc,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined ,RollbackOutlined, RiseOutlined} from '@ant-design/icons';
import {
  use_xygl_initformdata, use_xygl_initformdata_view, use_xygl_lsmx_initcolmun
} from './use_htzx_config.js';

import Xygl_lsmx_hook from './xygl_lsmx_hook.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route'


const Xygl_form = () => {
  const [lsmx_columnarr, setlsmx_columnarr] = useState(use_xygl_lsmx_initcolmun)
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    dict_htmb: [], query_gys: [], query_ry: []
  })
  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const [lsmxdata, setlsmxdata] = useState([])
  const [isloading, setisloading] = useState(false)
  const [delidarr, setdelidarr] = useState([])
  const [cswjm,setcswjm] = useState('')

  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])

  const init = async () => {
    var dictObj = await use_dict_byzdmc(["dict_syfw"])
    var bbObj = await use_olreport_bybbbm(["query_ry", "query_gys", "query_wl"])
    
    dynDatasObject.dict_syfw = dictObj.dict_syfw
    
    dynDatasObject.query_ry = bbObj.query_ry
    dynDatasObject.query_gys = bbObj.query_gys
    dynDatasObject.query_wl = bbObj.query_wl
    setdynDatasObject({ ...dynDatasObject })
  }

  //主表数据
  const [formdata, setformdata] = useState(JSON.parse(storage.pre_xygl_item).type != "view" ? use_xygl_initformdata : use_xygl_initformdata_view)
  const { setnowroute, collapsed } = useStore();


  //加载主表数据
  const loadformdata = async (id) => {
    await init()
    let rtdata = await fetchsync_util("/admin/htzx/query_xygl_byid", 'POST', { id }, "json")
    
    rtdata.resultdata.formdata.xybb = parseFloat(rtdata.resultdata.formdata.xybb).toFixed(2)
    rtdata.resultdata.formdata.syfw = rtdata.resultdata.formdata.syfw ? rtdata.resultdata.formdata.syfw.split(",") : []
    setcswjm(rtdata.resultdata.formdata.fj)
    
    console.log("当前用于渲染页面的数据为：",rtdata.resultdata.formdata)
    rtdata.resultdata.lsbbdata.forEach(item => {
      item.bbh = parseFloat(item.bbh).toFixed(2)
      item.fbrq = item.fbrq ? convertISODateTimeToYYYYMMDD(item.fbrq) : ""
    })
    
    setlsmxdata(rtdata.resultdata.lsbbdata)
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
  }

  // 页面进入加载数据
  useEffect(() => {
    if (JSON.parse(storage.pre_xygl_item).type == "edit") {
    
      loadformdata(JSON.parse(storage.pre_xygl_item).data.id)
      
     
    }
    else if (JSON.parse(storage.pre_xygl_item).type == "add") {
      init()
    }
    else {
      loadformdata(JSON.parse(storage.pre_xygl_item).data.id)
    }
  }, [])

  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


const handleupdate = async () => {
  if(cswjm != formdata.fj.value){
   let rtdata = await fetchsync_util("/admin/htzx/update_xygl", 'POST', { formdata }, "json")
   rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
   dropByCacheKey('xygl_list')
    dropByCacheKey('xygl_form')
    setnowroute({ route: "/shipSRM/htzx/xygl_list", title: "协议管理", closeroute: "/shipSRM/htzx/xygl_form" })

  }else{
    openNotification_util("当前上传附件未更新，请上传新的附件再更新")
    return;
  }


}


  const handleupload = async () => {
    console.log(formdata)

    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。

    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage); return; }
    else;

    if(JSON.parse(storage.pre_xygl_item).type == "edit"){
      if(cswjm != formdata.fj.value){
        openNotification_util("当前上传附件已更新，请点击更新按钮")
        return;
      }
    }

    //设置submit url
    var uploadurl = JSON.parse(storage.pre_xygl_item).type == "add" ?
      "/admin/htzx/add_xygl" : "/admin/htzx/edit_xygl";
    let newformdata = formdata;
    // newformdata.mbnr.value = JSON.parse(storage.tinymce_content);
    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata: newformdata }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    // setformdata(rtdata.resultdata.formdata);

    dropByCacheKey('xygl_list')
    dropByCacheKey('xygl_form')
    setnowroute({ route: "/shipSRM/htzx/xygl_list", title: "协议管理", closeroute: "/shipSRM/htzx/xygl_form" })

  }

  const handleBackTolist = () => {
    dropByCacheKey('xygl_list')
    dropByCacheKey('xygl_form')
    setnowroute({ route: "/shipSRM/htzx/xygl_list", title: "协议管理", closeroute: "/shipSRM/htzx/xygl_form" })
  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "5.9vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}
    data-page-type="form">

      <div style={{width:"100%",height:"100%",backgroundColor:"white",overflow:"auto"}}>
      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%", backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24"
      }}>

        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        {JSON.parse(storage.pre_xygl_item).type != "view" ?
          <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
            &nbsp;&nbsp;&nbsp;&nbsp;
            {JSON.parse(storage.pre_xygl_item).type == "edit" ? <Button type="default" onClick={handleupdate}
              style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
              <RiseOutlined />更新</Button> : ""}&nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={handleupload}
              style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
              <SaveOutlined />{JSON.parse(storage.pre_xygl_item).type == "add" ? "保存" : "修改"}</Button>
          </div>
          :
          <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <Button type="default" onClick={handleBackTolist}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
            <RollbackOutlined />返回列表</Button>
          </div>
        }
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        {/* 主表区域结束 */}
        <Divider></Divider>
        <div
          style={{
            height: "1.2rem",
            marginLeft: "2%",
            position: "relative",
            width: "96%",
            textIndent: "0.5rem",
            color: "#666666",
            backgroundColor: "white",
            lineHeight: "1.2rem",
            fontSize: "14px",
            fontWeight: "500",
            textAlign: "left",
            borderLeftStyle: "solid",
            borderWidth: "0.3rem",
            borderColor: "#a91f24",
            marginTop: "1rem",
            marginBottom: "0.5rem",
            letterSpacing: "0.05rem"
          }}
        >
          历史版本
        </div>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {isloading ?
            (<div style={{ width: "10%", height: "10%", position: "absolute", left: "50%", top: "49%", color: "#14d9cc" }}>            <LoadingOutlined /></div>)
            :
            <div style={{ position: "relative", width: "100%", overflowX: "auto", marginBottom: "1rem" }}>
              {switche && <Xygl_lsmx_hook colmuns={lsmx_columnarr} datasource={lsmxdata}
                onepageheight="10vh"
                styleobj={{ height: "70%" }}
                dynDatasObject={dynDatasObject}
                formdata={formdata}
                handledelid={ids => { ids.length !== 0 ? setdelidarr([...delidarr, ...ids]) : ''; }}
                handgetmxdata={(tabledata) => {
                  addkey_for_mxdata(tabledata)
                  setlsmxdata(tabledata)
                }}
                handlechangeFormdata={(data) => {
                  setformdata(data)
                }}
                forceupdate={forceupdate}
              />}</div>
          }
        </div>
      </div>
      </div>
    </div>
  )
}


export default Xygl_form
var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1vw", paddingRight: "1vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "98%", position: "relative", backgroundColor: "white", color: "#666",
    borderRadius: "10px", paddingBottom: "2rem", overflow: "visible"
  },
}